package com.ll.blog.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ll.blog.common.ApiResponse;
import com.ll.blog.common.IPUtils;
import com.ll.blog.contant.BehaviorEnum;
import com.ll.blog.contant.ExceptionEnum;
import com.ll.blog.entity.Behavior;
import com.ll.blog.service.IBehaviorService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.ll.blog.common.IPUtils.getIpAddr;

/**
 * 行为记录模块
 * @author 
 * @since 2023-10-25
 */
@Validated
@RestController
@RequestMapping("/behavior")
public class BehaviorController {
    @Resource
    private IBehaviorService behaviorService;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * @param time 时间
     * @param ip ip
     * @param period 周期 1 YEAR ,1 MONTH ,1 WEEK
     */
    @GetMapping("/behavior/count")
    public ApiResponse getAll(String time,String ip,String period){
        QueryWrapper<Behavior> wrapper = new QueryWrapper<>();
        QueryWrapper<Behavior> queryWrapper = new QueryWrapper<>();
        wrapper.select("action","count(distinct ip) as count").eq("type",BehaviorEnum.ARTICLE_MODULE).groupBy("action");
       queryWrapper.select("type","count(distinct ip) as count").ne("type",BehaviorEnum.ARTICLE_MODULE).groupBy("type");
        if(ip != null &&!ip.isEmpty()){
            wrapper.eq("ip",ip);
            queryWrapper.eq("ip",ip);
        }

        if(time != null &&!time.isEmpty()){
            wrapper.apply("date_format(create_time,'%Y-%m-%d') = '" + time+"'");
            queryWrapper.apply("date_format(create_time,'%Y-%m-%d') = '" + time+"'");
        }
        if(period != null &&!period.isEmpty()){
            String s = String.format("DATE_SUB(CURDATE(), INTERVAL %s) <= date(%s)", period, "create_time");
            System.out.println(s);
            wrapper.apply(s);
            queryWrapper.apply(s);
        }

        Map<String, Object> result = new HashMap<String,Object>();

        List<Map<String, Object>> map = behaviorService.listMaps(wrapper);
        List<Map<String, Object>> map1 = behaviorService.listMaps(queryWrapper);
        result.put("article",map);
        result.put("other",map1);
        return ApiResponse.success(result);
    }

    /**
     * 记录文章访问次数
     * @param id 文章id
     * @return
     */
    @GetMapping("/add")
    public ApiResponse record(@NotNull Integer id, HttpServletRequest request){
        String ip = getIpAddr(request);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",id.toString());
        map.put("ip",ip);
        map.put("type",BehaviorEnum.ARTICLE_MODULE.getValue());
        String s = JSON.toJSONString(map);
        if(operations.get(s)==null){
            Behavior behavior = new Behavior();
            behavior.setIp(ip);
            behavior.setAction(id.toString());
            behavior.setType(BehaviorEnum.ARTICLE_MODULE);
            behaviorService.save(behavior);
            operations.set(s,s,6,TimeUnit.HOURS);
        }
        return ApiResponse.success();
    }

    /**
     *获取所有ip
     */
    @GetMapping("/behavior/ip")
    public ApiResponse getIp(){
        QueryWrapper<Behavior> wrapper = new QueryWrapper<>();
        wrapper.lambda().select(Behavior::getIp).groupBy(Behavior::getIp);
        List<Object> list = behaviorService.listObjs(wrapper);
        return ApiResponse.success(list);
    }
}
